import axios,{ Axios, AxiosRequestConfig, AxiosResponse } from 'axios'
import baseStore from "@/store";
import md5 from 'md5'
interface BaseConfig {
  baseURL?:string
  timeout?:number
  headers?:{
    [name:string]: string
  }
}

interface AxiosResponse_<T = any> extends AxiosResponse {
  result:T,
  msg:string,
  url:string
}
export class Request{
  baseConfig: BaseConfig = {}
  axios!: Axios
  constructor(baseUrl?:string|undefined,loading:boolean = true,timeout:number = 30000){
    this.baseConfig.baseURL = baseUrl || import.meta.env.VITE_URL_BASE
    this.baseConfig.timeout = timeout
    this.axios = axios.create({
      ...this.baseConfig,
    });
    this.interceptors(loading)
  }
  private interceptors(loading:boolean){
    let elLoading:any
    // 添加请求拦截器
    this.axios.interceptors.request.use((config:any) => {
      // let store = baseStore()
      if(config.loading ? true : loading){
        elLoading = ElLoading.service({
          lock: true,
          text: 'Loading',
          background: 'rgba(0, 0, 0, 0.7)',
        })
      }
      let store = baseStore()
      config.headers.Ys_sso_sessionid = store.token 
      // 在发送请求之前做些什么
      return config;
    }, (error) => {
      // 对请求错误做些什么
      return Promise.reject(error);
    });
    // 添加响应拦截器
    this.axios.interceptors.response.use((response) => {
      // 对响应数据做点什么
      elLoading?.close()
      if(response.data.code === 0 || response.data.code === 200){
        return response.data.result || response.data.data;
      }else{
        ElMessage.error(response.data.message)
      }
    }, (error) => {
      // 对响应错误做点什么
      elLoading?.close()
      return Promise.reject(error);
    });
  }
  getSendData(data:object) {
    const timestamp = new Date().getTime();
    const nonce = Math.floor(Math.random() * (1 - 100) + 100);
    const sign = md5(`${timestamp}||${nonce}||yueworld`);
    const sendData = Object.assign({}, data, {
      timestamp,
      nonce,
      sign
    });
    return sendData;
  }
  request(config: AxiosRequestConfig<any>): Promise<AxiosResponse_>{
    return this.axios.request(config);
  }
  get(url:string, config?: AxiosRequestConfig<any> | undefined): any{
    return this.axios.get(url,{
      ...config,
      params: this.getSendData(config?.params)
    });
  }
  post(url:string,data: object = {},config?: AxiosRequestConfig<any> | undefined): any{
    return this.axios.post(url,this.getSendData(data), config);
  }
}